package com.ts.api.http.org.base;

import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.asymmetric.RSA;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.ts.api.http.org.base.entity.apply.BaseOrgApplyXiaMenZhongHongJiaYe;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.core.utils.ApiFieldConverter;
import com.ts.api.module.api.convert.org.handler.ApiOrgPhoneMd5ConvertHandler;
import com.ts.api.module.api.convert.org.model.RespOrgPhoneMd5Apply;
import com.ts.api.module.api.convert.org.model.RespOrgPhoneMd5DataExchange;

import java.util.Map;

import static com.gitee.apanlh.web.http.HttpContentType.APPLICATION_JSON;

/**
 *  中弘嘉业
 *
 *  @author 李源聪
 */
public class ApiOrgPhoneMd5ZhongHongJiaYe implements ApiOrgPhoneMd5ConvertHandler {

    private final String code;
    private final String publicKey;

    public ApiOrgPhoneMd5ZhongHongJiaYe(String code, String publicKey) {
        this.code = code;
        this.publicKey = publicKey;
    }

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) throws Exception {
        apiDataExchangeParameter.setHttpContentType(APPLICATION_JSON);
        Map<Object, Object> hashMap = MapUtils.newHashMap(newMap -> {
            newMap.put("channelCode", code);
            newMap.put("phone", apiDataExchangeParameter.getPhoneMd5());
        });
        return JsonUtils.toJson(hashMap);
    }

    @Override
    public RespOrgPhoneMd5DataExchange respDataExchange(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespOrgPhoneMd5DataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 0)) {
            return RespOrgPhoneMd5DataExchange.ofFail();
        }
        return RespOrgPhoneMd5DataExchange.ofSuc();
    }

    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) throws Exception {

        apiApplyParameter.setHttpContentType(APPLICATION_JSON);

        BaseOrgApplyXiaMenZhongHongJiaYe data = new BaseOrgApplyXiaMenZhongHongJiaYe();
        RSA rsa = new RSA(publicKey, null);
        // 渠道编号
        data.setChannelCode(code);
        // 手机号（RSA加密后）
        data.setPhone(rsa.encryptToBase64Str(apiApplyParameter.getPhone()));
        // 身份证号码(RSA加密后)
        if (ValidParam.isNotEmpty(apiApplyParameter.getIdcard())) {
            data.setIdCardNo(rsa.encryptToBase64Str(apiApplyParameter.getIdcard()));
        }
        // 姓名(RSA加密后)
        data.setName(rsa.encryptToBase64Str(apiApplyParameter.getUserName()));
        //  贷款额度/单位:万元
        if (ValidParam.isNotEmpty(apiApplyParameter.getLoanAmount())) {
            Integer money = ChooseEq.create()
                    .when(apiApplyParameter.getLoanAmount(), "1", 3)
                    .when(apiApplyParameter.getLoanAmount(), "2", 5)
                    .when(apiApplyParameter.getLoanAmount(), "3", 10)
                    .when(apiApplyParameter.getLoanAmount(), "4", 20)
                    .end();
            data.setLoanAmount(money);
        }

        // 借款期限 1.1个月 2.3个月 3.6个月 4.9个月 5.12个月 6.24个月 7.36个月 8.36个月以上
        data.setLoanLimit("1");

        //  借款用途 1.购车贷款 2.购房贷款 3.装修贷款 4.教育贷款 5.消费贷款 6.过桥贷款 7.结婚贷款 8.旅游贷款 9.医疗贷款 10.其他贷款
        if (ValidParam.isNotEmpty(apiApplyParameter.getLoanPurpose())) {
            String value = ChooseEq.create()
                    .when(apiApplyParameter.getLoanPurpose(), "1", "8")
                    .when(apiApplyParameter.getLoanPurpose(), "2", "4")
                    .when(apiApplyParameter.getLoanPurpose(), "3", "7")
                    .when(apiApplyParameter.getLoanPurpose(), "4", "3")
                    .when(apiApplyParameter.getLoanPurpose(), "5", "9")
                    .when(apiApplyParameter.getLoanPurpose(), "6", "5")
                    .end("10");
            data.setLoanUse(value);
        }

        // 性别 1:男 2:女 3:未知
        String sex = apiApplyParameter.getSex();
        if (ValidParam.isNotEmpty(sex)) {
            String sexChoose = ChooseEq.create()
                    .when(sex, "0", "1")
                    .when(sex, "1", "2")
                    .end("3");
            data.setSex(sexChoose);
        }

        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiApplyParameter);

        data.setAge(apiFieldConverter.getAgeInt());
        // 工作城市,结尾不要带‘市’
        data.setCityOfWork(apiApplyParameter.getCity().replace("市", ""));
        // 工作城市代码，重庆：500100
        data.setCityOfWorkCode(Integer.valueOf(apiApplyParameter.getAreaCode()));

        // 月收入/元
        data.setRevenue(apiFieldConverter.getMonthlySalaryNumber());

        // 职业 0.无固定职业 1.工薪族 2.生意人
        if (ValidParam.isNotEmpty(apiApplyParameter.getCareer())) {
            String career = ChooseEq.create()
                    .when(apiApplyParameter.getCareer(), "1", "1")
                    .when(apiApplyParameter.getCareer(), "2", "0")
                    .when(apiApplyParameter.getCareer(), "3", "2")
                    .when(apiApplyParameter.getCareer(), "4", "1")
                    .when(apiApplyParameter.getCareer(), "5", "0")
                    .end();
            data.setProfession(career);
        }

        // 公积金 0.无 1.有
        if (ValidParam.isNotEmpty(apiApplyParameter.getProvidentFund())) {
            String gongjijin = ChooseEq.create()
                    .when(apiApplyParameter.getProvidentFund(), "1", "0")
                    .when(apiApplyParameter.getProvidentFund(), "2", "1")
                    .when(apiApplyParameter.getProvidentFund(), "3", "1")
                    .when(apiApplyParameter.getProvidentFund(), "4", "1")
                    .end("0");
            data.setReservedFunds(gongjijin);
        }

        // 社保 0.无 1.有
        if (ValidParam.isNotEmpty(apiApplyParameter.getSocialSecurity())) {
            String shebao = ChooseEq.create()
                    .when(apiApplyParameter.getSocialSecurity(), "1", "0")
                    .when(apiApplyParameter.getSocialSecurity(), "2", "1")
                    .when(apiApplyParameter.getSocialSecurity(), "3", "1")
                    .when(apiApplyParameter.getSocialSecurity(), "4", "1")
                    .end("0");
            data.setSocialSecurity(shebao);
        }

        // 信用卡 0.无 1.有
        if (ValidParam.isNotEmpty(apiApplyParameter.getCreditLimit())) {
            String shebao = ChooseEq.create()
                    .when(apiApplyParameter.getCreditLimit(), "1", "0")
                    .when(apiApplyParameter.getCreditLimit(), "2", "1")
                    .when(apiApplyParameter.getCreditLimit(), "3", "1")
                    .when(apiApplyParameter.getCreditLimit(), "4", "1")
                    .when(apiApplyParameter.getCreditLimit(), "5", "1")
                    .when(apiApplyParameter.getCreditLimit(), "6", "1")
                    .end("0");
            data.setCreditCard(shebao);
        }

        //  芝麻分 0.无 1.550分以下 2.550-600分 3.600-650分 4.650-700分 5.700分及以上
        if (ValidParam.isNotEmpty(apiApplyParameter.getSesameCredit())) {
            String shebao = ChooseEq.create()
                    .when(apiApplyParameter.getSesameCredit(), "1", "2")
                    .when(apiApplyParameter.getSesameCredit(), "2", "3")
                    .when(apiApplyParameter.getSesameCredit(), "3", "4")
                    .when(apiApplyParameter.getSesameCredit(), "4", "5")
                    .end("1");
            data.setZhima(shebao);
        }

        // 车产 0.无 1.有
        if (ValidParam.isNotEmpty(apiApplyParameter.getCarInfo())) {
            String car = ChooseEq.create()
                    .when(apiApplyParameter.getCarInfo(), "1", "0")
                    .when(apiApplyParameter.getCarInfo(), "2", "1")
                    .when(apiApplyParameter.getCarInfo(), "3", "1")
                    .when(apiApplyParameter.getCarInfo(), "4", "1")
                    .end("0");
            data.setCar(car);
        }

        // 房产 0.无 1.本地房 2.外地房
        if (ValidParam.isNotEmpty(apiApplyParameter.getRealEstateInfo())) {
            String house = ChooseEq.create()
                    .when(apiApplyParameter.getRealEstateInfo(), "1", "0")
                    .when(apiApplyParameter.getRealEstateInfo(), "2", "1")
                    .when(apiApplyParameter.getRealEstateInfo(), "3", "1")
                    .when(apiApplyParameter.getRealEstateInfo(), "4", "1")
                    .when(apiApplyParameter.getRealEstateInfo(), "5", "1")
                    .when(apiApplyParameter.getRealEstateInfo(), "6", "1")
                    .end("0");
            data.setHouse(house);
        }

        // 寿险保单 0.无 1.有
        data.setInsurance("0");

        //  学历 学历 0.高中及以下 1.大专 2.本科 3.本科以上
        if (ValidParam.isNotEmpty(apiApplyParameter.getEducationAttainment())) {
            String edu = ChooseEq.create()
                    .when(apiApplyParameter.getEducationAttainment(), "1", "0")
                    .when(apiApplyParameter.getEducationAttainment(), "2", "0")
                    .when(apiApplyParameter.getEducationAttainment(), "3", "0")
                    .when(apiApplyParameter.getEducationAttainment(), "4", "1")
                    .when(apiApplyParameter.getEducationAttainment(), "5", "2")
                    .when(apiApplyParameter.getEducationAttainment(), "6", "3")
                    .end("0");
            data.setEducation(edu);
        }

        //  工资代发 0.无 1.有
        if (ValidParam.isNotEmpty(apiApplyParameter.getSalaryPayMethod())) {
            String salary = ChooseEq.create()
                    .when(apiApplyParameter.getSalaryPayMethod(), "1", "1")
                    .when(apiApplyParameter.getSalaryPayMethod(), "2", "0")
                    .when(apiApplyParameter.getSalaryPayMethod(), "3", "0")
                    .end("0");
            data.setSalary(salary);
        }

        //  营业执照 0.无 1.有
        if (ValidParam.isNotEmpty(apiApplyParameter.getBizLicenseYear())) {
            String bizLicenseYear = ChooseEq.create()
                    .when(apiApplyParameter.getBizLicenseYear(), "1", "0")
                    .when(apiApplyParameter.getBizLicenseYear(), "2", "1")
                    .when(apiApplyParameter.getBizLicenseYear(), "3", "1")
                    .when(apiApplyParameter.getBizLicenseYear(), "4", "1")
                    .end("0");
            data.setBusinessLicense(bizLicenseYear);
        }
        // 备注字段
        data.setRemark(apiApplyParameter.getFormRemark());
        return JsonUtils.toJson(data);
    }

    @Override
    public RespOrgPhoneMd5Apply respApply(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespOrgPhoneMd5Apply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 0)) {
            return RespOrgPhoneMd5Apply.ofFail();
        }
        return RespOrgPhoneMd5Apply.ofSuc();
    }
}
